package com.cqupt.scanning.system.acl.helper;


import com.cqupt.scanning.system.acl.entity.AclPermission;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 根据权限数据构建菜单数据
 * </p>
 *
 * @author 宋宝梁
 */
public class PermissionHelper {

    /**
     * 使用递归方法建菜单
     * @param treeNodes
     * @return
     */
    public static List<AclPermission> bulid(List<AclPermission> treeNodes, boolean isAdmin) {
        List<AclPermission> trees = new ArrayList<>();
        if (isAdmin) {
            for (AclPermission treeNode : treeNodes) {
                if (treeNode.getPid() == 0) {
                    treeNode.setLevel(1);
                    trees.add(findChildren(treeNode,treeNodes));
                }
            }
            return trees;
        }

        for (AclPermission treeNode : treeNodes) {
            if (treeNode.getPid() == 1) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;

    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    private static AclPermission findChildren(AclPermission treeNode, List<AclPermission> treeNodes) {
        treeNode.setChildren(new ArrayList<AclPermission>());

        for (AclPermission it : treeNodes) {
            if(treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }
}
